/* eslint-disable */
import axios from 'axios'
import { config} from './config.js'
import { Toast, Dialog } from "mand-mobile"
import store from "@/tools/factory"
import router from '@/router'
let model_401 = false;
import * as module from "@/tools/util";
const service = axios.create({
    timeout: 10000
})


let gwsignSwitch = true
import { getGwsignConfig, isUrlHasNull, bodyHasNullOrUndefined, undefinedFifter } from '@/tools/gwsign'
//添加请求拦截器
service.interceptors.request.use(function (userConfig) {
    // console.log(userConfig, 'userLogin')
   /* let routerInfo = store.get("routerInfo");
    let areaid = undefinedFifter(routerInfo.areaId);
    let lat = undefinedFifter(store.get("lat"));
    let lng = undefinedFifter(store.get("lng"));
    let DefaultHeader = {
        'content-type': 'application/json',
        'v': '1.0',
        'token': store.get("token") || "",
        'osVersion': "h5",
        'appVersion': config.appVersion,
        'appName': 'qx_h5',
        'areaId': areaid ? areaid : 0,
        'lat': lat ?  lat : 0,
        'lng': lng ? lng : 0,
    }*/
    // userConfig.headers = DefaultHeader
    return userConfig
}, function (error) {
    return Promise.reject(error)
})
//添加响应拦截器
service.interceptors.response.use(function (response) {
    // return response.data
    //     console.log(response, 'response')
        return response
}, function (error) {
    if (error.response.config.headers.type) {
        Toast.failed(error.response.data.msg);
    }
    return Promise.reject(error)
}
)

/*//undefined 过滤器
function undefinedFifter(str) {
    if (!str) {
        return false
    }
    if (JSON.stringify(str).includes("undefined") || JSON.stringify(str).includes("Undefined")) {
        return false
    } else {
        return str
    }
}*/

export default {
    request(url, method, data, type, noToken) {
        let routerInfo = store.get("routerInfo");
        let bikeBaseUrl = `${routerInfo.bikeBaseUrl}/`;
        let userBaseUrl = `${routerInfo.userRouter}/`;
        let baseUrl = null;

        let areaid = undefinedFifter(routerInfo.areaId);
        let lat = undefinedFifter(store.get("lat"));
        let lng = undefinedFifter(store.get("lng"));
        let DefaultHeader = {
            'content-type': 'application/json',
            'v': '1.0',
            'token': store.get("token") || "",
            'osVersion': "h5",
            'appVersion': config.appVersion,
            'appName': 'qx_h5',
            'areaId': areaid ? areaid : 0,
            'lat': lat ?  lat : 0,
            'lng': lng ? lng : 0,
        }

        // 添加签名
        let hasNull = isUrlHasNull(url)
        // console.log(data, 'data')
        let dataCopy = data ? JSON.parse(JSON.stringify(data)) : {}
        let hasBodyNullOrUndefined = bodyHasNullOrUndefined(dataCopy)
        // url中有/null 或者 body中有null值和undefined值的时候不走验签
        if (hasNull) {
            console.log('url中有null')
            return new Promise((resolve, reject) => {
                reject(false);
            })
        }
        if (!hasNull) {
            let gwsignConfig = getGwsignConfig(url, dataCopy)
            Object.assign(DefaultHeader, {
                'gwsign': gwsignConfig.gwsign,
                't': gwsignConfig.t,
                's': gwsignConfig.s
            })
        }

        if (type == 1) {
            baseUrl = config.baseURL
        }
        if (type == 2) {
            baseUrl = bikeBaseUrl
        }
        if (type == 3) {
            baseUrl = userBaseUrl
        }
        let requestData = {};
        if (method == "get") {
            requestData = {
                headers: DefaultHeader,
                method: method,
                url: `${baseUrl}${url}`,
                params: data
            }
        } else {
            requestData = {
                headers: DefaultHeader,
                method: method,
                url: `${baseUrl}${url}`,
                data: data,
            }
        }
        return new Promise((resolve, reject) => {
            service(requestData).then(res => {  //axios返回的是一个promise对象
                if (url.indexOf('rider/api/v3/login') != -1) {
                    resolve(res)
                } else {
                    resolve(res.data)  //resolve在promise执行器内部
                }

            }).catch(err => {
                let error = err.response;
                if (!error) {
                    Toast.failed("服务器未响应");
                    return false
                }
                if (error.status == 401) {
                    if (model_401) {
                        return false
                    }
                    model_401 = true;
                    module.removeStorages(['billNo', 'loginInfo', 'isAuth', 'regRoute', 'depositInfo', 'rideInfo', 'riding', 'reserve', 'appointment', 'orderno', "parkPay", 'gwsSalt', "unionOpenId"]);
                    Toast.hide();
                    Dialog.confirm({
                        title: '重新登录',
                        content: '登录过期，请重新登录后用车',
                        confirmText: '确定',
                        onConfirm: function () {
                            model_401 = false;
                            router.push({
                                path: 'mobileLogin'
                            })
                        }
                    })
                    return false
                }
                Toast.failed("小遛出错咯，请稍后重试");
                reject(error)
            })
        })
    }
}

